package com.x.uikit.page;

import android.content.Context;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;

/**
 * 提供XPage的UI环境,一共分为3个层，从下到上为：
 * 1、page页面层
 * 2、弹窗面板层
 * 3、扩展层
 */
public class XPageEnvironment extends FrameLayout {
    private final XPageLayer mPageLayer;
    private final XPageLayer mPanelLayer;
    private final XPageLayer mExtendLayer;

    public XPageEnvironment(@NonNull Context context) {
        super(context);
        mPageLayer = new XPageLayer(getContext());
        this.addView(mPageLayer, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mPanelLayer = new XPageLayer(getContext());
        this.addView(mPanelLayer, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mExtendLayer = new XPageLayer(getContext());
        this.addView(mExtendLayer, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    }

    @NonNull
    public XPageLayer getExtendLayer() {
        return mExtendLayer;
    }

    @NonNull
    public XPageLayer getPageLayer() {
        return mPageLayer;
    }

    @NonNull
    public XPageLayer getPanelLayer() {
        return mPanelLayer;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (mExtendLayer.dispatchKeyEvent(event)) {
            return true;
        }
        if (mPanelLayer.dispatchKeyEvent(event)) {
            return true;
        }
        if (mPageLayer.dispatchKeyEvent(event)) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    public boolean onBackPressed() {
        boolean handle = layerHandlerBackPressed(mExtendLayer);
        if (!handle) {
            handle = layerHandlerBackPressed(mPanelLayer);
        }
        if (!handle) {
            handle = layerHandlerBackPressed(mPageLayer);
        }

        return handle;
    }

    private boolean layerHandlerBackPressed(XPageLayer layer) {
        if (layer == null || layer.getChildCount() < 1) {
            return false;
        }
        return layer.onBackPressed();
    }
}
